package com.guo.dms.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.guo.dms.common.menu.entity.Menu;
import com.guo.dms.common.tree.entity.TreeNode;

public class RequestFilter implements Filter {
	FilterConfig filterConfig;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig=filterConfig;
		//可以获取应用程序上下文
		//filterConfig.getServletContext();
		System.err.println("");
	}

	@Override
	@SuppressWarnings({ "unchecked" })
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		initTreeNode(request);
		//执行其他的方法
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	
	 /**
	  * 将请求中含有request节点变更的请求进行拦截和变更
	  * @param request
	  */
	 private void initTreeNode(ServletRequest request){
			HttpServletRequest req =(HttpServletRequest) request;
			String leftBarMenuId=req.getParameter("selfNodeId");
			String headMenuId=req.getParameter("livebarId");
			TreeNode<Menu> userMenuTree =(TreeNode<Menu>)req.getSession().getAttribute("menuTree");
	 		if(headMenuId!=null && userMenuTree !=null){
				for (TreeNode<Menu> menuNode : userMenuTree.getChilds()) {
					if(menuNode.getNode().getId().toString().equals(headMenuId)){
						req.getSession().setAttribute("headerliveNode",menuNode); //当前激活的节点
						req.getSession().setAttribute("selfNode",menuNode.getChilds().get(0).getNode());
					}
				}
			}
			if(leftBarMenuId!=null && userMenuTree !=null){
				//设置到session中
				  TreeNode<Menu> tree = (TreeNode<Menu>)req.getSession().getAttribute("headerliveNode");
				  for (TreeNode<Menu> childtree : tree.getChilds()) {
					  if(childtree.getNode().getId().toString().equals(leftBarMenuId)){
						  req.getSession().setAttribute("selfNode",childtree.getNode());
					  }
				}
				 
			}
	 }
}
